﻿<%@ Page Title="Promotion Engine -  Report Setup" Language="C#" MasterPageFile="~/Site.Master"
    AutoEventWireup="true" CodeBehind="ReportDetail.aspx.cs" Inherits="PromotionEngine.ReportDetail" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
    <script type="text/javascript">
        var oCustomerPropertyLink = {};
        var oCustomer = {};
        var oItem = {};
        var oWarehouse = {};
        var oReferenceValue = {};
        var oSalesPerson = {};
        var oReportParameterLine = {};
        var oReportHeader = {};
        var jsonCustomer;
        var oCustomerPropertyDetail = {};
        var isInsert = "1";
        var gird;
        var girdDetail;
        var propertyForDetailID = 0;
        var reportID = 0;
        var isUpdate = false;
        var basePrice = 0;
        var selectItemID;
        var selectItemIndex = 0;
        var docDatePicker, docDueDatePicker;
        var record = 0;
        var docStatus = 1;
        var customerCombobox;
        var editRowIndex;
        var selectedCustomerID;
        function CreateNew() {
            $.ajax({
                type: "POST",
                url: "ReportDetail.aspx/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    location.href = "ReportDetail.aspx?reportID=0&IsUpdate=false";
                },
                failure: function (response) {
                },
                error: function (response) {
                }
            });
        }
        function OpenDocumentList() {
            var wnd = $("#reportList")
                        .kendoWindow({
                            title: "List of Reports",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 800,
                            height: 500,
                            content: { type: "POST", url: "ReportHeader.aspx" },
                            iframe: true
                        }).data("kendoWindow");

            wnd.center().open();
            wnd.bind('close', function () {
                $("#reportList").empty();
            });
        }
        function OpenBuildingQueryPage() {
            $("#buildingQuery").empty();
            var url = "";
            var title = "";
            url = "BuildingQuery.aspx?Query=" + $("#ReportQueryString").val();
            title = "Building Query String";

            if (url.length > 0) {
                var wnd = $("#buildingQuery")
                        .kendoWindow({
                            title: title,
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 800,
                            height: 550,
                            content: { type: "POST", url: url, data: {} },
                            iframe: true
                        }).data("kendoWindow");
                wnd.setOptions({
                    title: title
                });
                wnd.center().open();
            }
        }
        function ChooseQuery(query) {
            $("#ReportQueryString").text(query);
            $("#buildingQuery").data("kendoWindow").close();
        }

        function LoadReport(headerReportID, headerReportCode, headerReportName, headerReportType, headerReportUrl, headerReportQuertString) {
            
            $.ajax({
                type: "POST",
                url: "ReportDetail.aspx/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    grid.dataSource.data([]);
                    reportID = headerReportID;
                    $("#ReportID").val(headerReportID);
                    $("#ReportCode").val(headerReportCode);
                    $("#ReportName").val(headerReportName);
                    $("#ReportURL").val(headerReportUrl);
                    $("#ReportQueryString").text(headerReportQuertString);
                    isUpdate = true;
                    grid.dataSource.read();
                    $("#reportList").empty();
                    var url = "ReportDetail.aspx?ReportID=" + reportID + "&IsUpdate=true"
                    history.pushState({ reportID: reportID, IsUpdate: true }, "Document", url);
                },
                failure: function (response) {
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
            $("#reportList").data("kendoWindow").close();
        }
        window.addEventListener('load', function () {
            setTimeout(function () {
                window.addEventListener('popstate', function () {
                    location.href = document.location;
                });
            }, 0);
        });

        function pareTypeKendoComboBox(container, options) {
            $('<input required  validationMessage="Pls select Data Type."  data-text-field="ReferenceName" data-value-field="ReferenceValue" Name="ParaType" ID="ParaType" data-bind="value:' + options.field + '"/>')
                        .appendTo(container)
                        .kendoComboBox({
                            autoBind: false,
                            filter: "contains",
                            placeholder: "[Select Data Type]",
                            suggest: true,
                            dataSource: oReferenceValue,
                            change: function (e) {
                                var cmb = this;
                                if (cmb.selectedIndex < 0) {
                                    cmb.value(null); // or set to the first item in combobox
                                }
                            }
                        });
            $('<span class="k-invalid-msg" data-for="ParaType"></span>').appendTo(container);
        }
        function GetReference() {
            $.ajax({
                type: "GET",
                url: "ReportDetail.aspx/GetAllReferenceValue",
                data: {
                    referenceCode: kendo.stringify('ParaType')
                },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    oReferenceValue = $.parseJSON(response.d);
                },
                failure: function (response) {
                    alert(response.d);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (jqXHR.status == 500) {
                        alert('Internal error: ' + jqXHR.responseText);
                    } else {
                        alert('Unexpected error.' + jqXHR.responseText);
                    }
                }
            });
        }

        var selectedRow;
        $(document).ready(function () {
            GetReference();
            isUpdate = '<%= Request.QueryString["IsUpdate"] %>';
            $('#ReportID').val('<%= Request.QueryString["ReportID"] %>');
            reportID = $('#ReportID').val();
            if (reportID == '0') {
                //Do something  
            }
            else {
                GetHeaderByReportID();
            }

            //Clear Session
            $.ajax({
                type: "POST",
                url: "ReportDetail.aspx/ClearSessionData",
                data: '',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    //Load Grid
                    grid = $("#grid").kendoGrid({
                        dataSource: {
                            transport: {
                                read: {
                                    type: "GET",
                                    url: "ReportDetail.aspx/GetReportParameter",
                                    data: '',
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json",
                                    complete: function (jqXHR, textStatus) { }
                                },
                                destroy: {
                                    type: "GET",
                                    url: "ReportDetail.aspx/DeleleReportParameter",
                                    contentType: "application/json; charset=utf-8",
                                    dataType: "json"
                                },
                                create: {
                            },
                            parameterMap: function (data, operation) {
                                if (operation === "read") {
                                    return { reportID: reportID };
                                }
                                if (operation === "destroy") {
                                    return { reportDetailID: data.ReportDetailID };
                                }
                            },
                            serverPaging: true,
                            serverSorting: true,
                            serverFiltering: true
                        },
                        type: "odata", //Important!!!!
                        schema: {
                            data: function (a) {
                                if (a.d != null) {
                                    var data = a.d.Data;
                                    return data;
                                }
                            },
                            total: "d.Count",
                            model: {
                                id: "ReportDetailID",
                                fields: {
                                    ReportID: { type: "string" },
                                    ReportDetailID: { type: "string" },
                                    ParaName: { type: "string", validation: { required: { message: "Name is required"}} },
                                    ParaCaption: { type: "string", validation: { required: { message: "Caption is required"}} },
                                    ParaType: { type: "string" },
                                    PareFromQuery: { type: "string" },
                                    ReferenceName: { type: "string" }
                                }
                            }
                        }
                    },
                    sortable: true,
                    resizable: true,
                    height: 330,
                    selectable: "row",
                    toolbar: [{ name: 'create', text: 'Add New Parameter' }, { name: 'excel'}],
                    excel: {
                        fileName: "Report Parameter Line.xlsx",
                        filterable: true
                    },
                    batch: true,
                    columns: [
                            { field: "ReportID", title: "ReportID", width: 100, hidden: true },
                            { field: "ReportDetailID", title: "ReportDetailID", width: 150, hidden: true },
                            { field: "ParaName", title: "Name", width: 200 },
                            { field: "ParaCaption", title: "Caption", width: 300 },
                            { field: "ParaType", title: "Data Type", width: 200, editor: pareTypeKendoComboBox, template: "#=ReferenceName#" },
                            { field: "ParaFromQuery", title: "Query", width: 400 },
                            { command: ["edit", "destroy"], title: "Action", width: "200px" }
                            ],
                    editable: {
                        mode: "inline",
                        confirmation: "Are you sure you want to remove this item?",
                        createAt: "bottom"
                    },
                    edit: function (e) {
                        if (e.model.isNew()) {
                            $("a.k-grid-update")[0].innerHTML = "<span class='k-icon k-update'></span>Save";
                            isInsert = "1";
                        }
                        else {

                            isInsert = "2";
                        }
                    },
                    save: function (e) {
                        var listTextBox = $("input:text");
                        for (var i = 0; i < listTextBox.length; i++) {
                            var name = listTextBox[i].name;
                            if (name.length > 0) {
                                oReportParameterLine[name] = $("[name=" + name + "]").val();
                            }
                        }
                        oReportParameterLine.ParaType = $('#ParaType').data("kendoComboBox").value();
                        oReportParameterLine.ReferenceName = $('#ParaType').data("kendoComboBox").text();
                        //Update or Insert Item
                        $.ajax({
                            type: "POST",
                            url: "ReportDetail.aspx/UpdateReport",
                            data: JSON.stringify({
                                oReportParameterLine: JSON.stringify(oReportParameterLine),
                                isInsert: isInsert
                            }),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (data) {
                                grid.dataSource.read();
                            },
                            error: function (xhr, status, err) {
                                var err = eval("(" + xhr.responseText + ")");
                                alert(err.Message);
                            }
                        });
                    },
                    dataBound: onDataBound
                }).data("kendoGrid");
            },
            failure: function (response) {
                if (jqXHR.status == 500) {
                    alert('Internal error: ' + jqXHR.responseText);
                } else {
                    alert('Unexpected error.' + jqXHR.responseText);
                }
            },
            error: function (response) {
                if (jqXHR.status == 500) {
                    alert('Internal error: ' + jqXHR.responseText);
                } else {
                    alert('Unexpected error.' + jqXHR.responseText);
                }
            }
        });
    });

    function onDataBound(e) {
        var grid = $("#grid").data("kendoGrid");

        $(grid.tbody).on("click", "td", function (e) {
            var row = $(this).closest("tr");
            editRowIndex = $("tr", grid.tbody).index(row);
            var colIdx = $("td", row).index(this);
        });
    }

    function UpdateProcess() {
        
        var validator = $("#aspnetForm").kendoValidator().data("kendoValidator");
        if (validator.validate()) {
            oReportHeader.ReportID = $("#ReportID").val();
            oReportHeader.ReportCode = $("#ReportCode").val(); 
            oReportHeader.ReportName = $("#ReportName").val();
            oReportHeader.ReportType = '3';
            oReportHeader.ReportURL = $("#ReportURL").val()
            oReportHeader.ReportQueryString = $("#ReportQueryString").val();
            $.ajax({
                type: "POST",
                url: "ReportDetail.aspx/UpdateReportToDB",
                data: JSON.stringify({
                    oReportHeader: JSON.stringify(oReportHeader),
                    isUpdate: isUpdate
                }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    if (data.d != "0") {
                        if ($.isNumeric(data.d)) {
                            isUpdate = 'true';
                            $('#ReportID').val(data.d);
                            reportID = data.d;
                            grid.dataSource.data([]);
                            $.ajax({
                                type: "POST",
                                url: "ReportDetail.aspx/ClearSessionData",
                                data: '',
                                contentType: "application/json; charset=utf-8",
                                dataType: "json",
                                success: function (response) {
                                    var url = "ReportDetail.aspx?ReportID=" + reportID + "&IsUpdate=true"
                                    history.pushState({ reportID: reportID, IsUpdate: true }, "Document", url);
                                    grid.dataSource.read();
                                },
                                failure: function (response) {
                                },
                                error: function (jqXHR, textStatus, errorThrown) {
                                    if (jqXHR.status == 500) {
                                        alert('Internal error: ' + jqXHR.responseText);
                                    } else {
                                        alert('Unexpected error.' + jqXHR.responseText);
                                    }
                                }
                            });
                            
                            setMasterMessage("Operation complete successful!", "success");
                        }
                        else {
                            
                            setMasterMessage(data.d, "error");
                        }
                    }
                    else {
                        
                        setMasterMessage(data.d, "error");
                    }
                },
                error: function (xhr, status, err) {
                    var err = eval("(" + xhr.responseText + ")");
                    alert(err.Message);
                }
            });
        }
    }

    function GetHeaderByReportID() {
        $.ajax({
            type: "POST",
            url: "ReportDetail.aspx/GetReportByReportID",
            data: JSON.stringify({
                reportID: reportID
            }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                var result = JSON.parse(response.d);
                if (result.Table) {
                    var docHeader = result.Table;
                    if (docHeader.length > 0) {
                        docHeader = docHeader[0];
                        reportID = docHeader.ReportID;
                        $('#ReportID').val(reportID);
                        setValueTextBox(docHeader);
                        $("#ReportQueryString").text(docHeader.ReportQueryString);
                        isUpdate = true;
                    }
                }
            },
            failure: function (response) {
                alert(response.d);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                if (jqXHR.status == 500) {
                    alert('Internal error: ' + jqXHR.responseText);
                } else {
                    alert('Unexpected error.' + jqXHR.responseText);
                }
            }
        });
    }
    </script>
    <table style="width: 100%;">
        <tr>
            <td style="width: 100px;">
                <label for="reportID">
                    Report ID</label>
            </td>
            <td style="width: 230px;">
                <input name="ReportID" id="ReportID" class="k-input k-textbox" type="text" readonly="readonly"
                    style="width: 200px;" />
            </td>
            <td style="width: 100px;">
                Report Code
            </td>
            <td style="width: 230px;">
                <input name="ReportCode" id="ReportCode" class="k-input k-textbox" type="text" required
                    validationmessage="Please input Code" style="width: 200;" />
            </td>
            <td style="width: 100px;">
                Report Name
            </td>
            <td>
                <input name="ReportName" id="ReportName" class="k-input k-textbox" type="text" required
                    validationmessage="Please input Name" style="width: 92%;" />
            </td>
        </tr>
        <tr>
            <td>
                Query String
            </td>
            <td colspan="6">
                <textarea rows="3" name="ReportQueryString" id="ReportQueryString" required validationmessage="Please input Query String"
                    class="k-input k-textbox" style="width: 96%; top: 0px; left: 0px;"> </textarea>
                <span class="k-icon k-i-search" style="margin-left: 0px; width: 16px; cursor: pointer;"
                    onclick="OpenBuildingQueryPage()" title="Building Query" id="spanChooseCustomer">
                </span>
            </td>
        </tr>
    </table>
    <hr />
    <div id="grid">
    </div>
    <div id="buildingQuery">
    </div>
    <div id="reportList">
    </div>
    <table style="width: 100%;" border="0">
        <tr>
            <td align="left" style="width: 70%">
                <div class="k-edit-buttons k-state-default">
                    <button type="button" id="btnSave" onclick="UpdateProcess();" class="k-button k-button-icontext k-primary"
                        style="width: 80px;">
                        <span class="k-icon k-update"></span>Save</button>
                    <button type="button" id="btnCreateNew" onclick="CreateNew();" class="k-button k-button-icontext k-primary"
                        style="width: 120px;">
                        <span class="k-icon k-i-plus"></span>Create New</button>
                    <button type="button" id="btnDocumentList" onclick="OpenDocumentList()" class="k-button k-button-icontext k-primary"
                        style="width: 130px;">
                        <span class="k-icon k-i-hbars"></span>Report List</button>
                </div>
            </td>
            <td>
            </td>
        </tr>
    </table>
</asp:Content>
